﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using System.Web;
using System.Web.Mvc;

namespace visu.Controllers.v1
{
    public class materialController : Controller
    {
        //
        // GET: /material/
        //手机APP:在库查询
        public ActionResult query()
        {
            var tempObj = new object();
            Stream postData = Request.InputStream;
            StreamReader sRead = new StreamReader(postData);
            string postContent = sRead.ReadToEnd();
            Dictionary<string, object> suggestions = Newtonsoft.Json.JsonConvert.DeserializeObject<Dictionary<string, object>>(postContent);
            string token = "";
            vcabinetmaterial vcm = new vcabinetmaterial();
            //查询条件
            List<SearchCondition> listSearch = new List<SearchCondition>();
            if (suggestions.Keys.Contains("token"))
            {
                token = suggestions["token"].ToString();
            }
            
            if (suggestions.Keys.Contains("m_code"))
            {
                vcm.M_CODE = suggestions["m_code"].ToString();
                if (vcm.M_CODE != "")
                {
                    SearchCondition M_CODE = new SearchCondition() { Field = "M_CODE", Operator = "co", Value = vcm.M_CODE };
                    listSearch.Add(M_CODE);
                }
            }
            if (suggestions.Keys.Contains("m_specification"))
            {
                vcm.M_SPECIFICATION = suggestions["m_specification"].ToString();
                if (vcm.M_SPECIFICATION != "")
                {
                    SearchCondition M_SPECIFICATION = new SearchCondition() { Field = "M_SPECIFICATION", Operator = "co", Value = vcm.M_SPECIFICATION };
                    listSearch.Add(M_SPECIFICATION);
                }
            }
            if (suggestions.Keys.Contains("m_type"))
            {
                vcm.M_TYPE = suggestions["m_type"].ToString();
                if (vcm.M_TYPE != "")
                {
                    SearchCondition M_TYPE = new SearchCondition() { Field = "M_TYPE", Operator = "=", Value = vcm.M_TYPE };
                    listSearch.Add(M_TYPE);
                }
            }

            var userobj=userController.check_token(token);
            if (userobj == null)
            {
                tempObj = new { code = "error",data="", message = "用户未登陆！" };
            }
            else
            {
                SearchCondition COMPANY_ID = new SearchCondition() { Field = "COMPANY_ID", Operator = "=", Value = userobj.COMPANY_ID.ToString()};
                listSearch.Add(COMPANY_ID);
                SearchCondition CAB_MARTERIAL_ID = new SearchCondition() { Field = "CAB_MARTERIAL_ID", Operator = "=", Value = userobj.COMPANY_ID.ToString() };
                Expression<Func<vcabinetmaterial, bool>> exp = SearchExpression.GetSearchExpression<vcabinetmaterial>(null, listSearch, null,null);

                var vcabinetmaterial = BLLSession.Current.vcabinetmaterialBLL.GetListBy(exp).ToList();
                var data = vcabinetmaterial.Where(p => p.CAB_MARTERIAL_ID != "" && p.CAB_MARTERIAL_ID != null);
                tempObj = new { code = "success", data = data, message = "查询成功！" };
            }
            return Json(tempObj, JsonRequestBehavior.AllowGet);
        }
        //手机APP:添加新物料类型
        public ActionResult add_type()
        {
            var tempObj = new object();
            string token = "";
            int total = 0;
            material mat = new material();
            if (Request.Form["token"]!=null)
            {
                token = Request.Form["token"].ToString();
                total++;
            }

            var userobj = userController.check_token(token);
            if (userobj == null || token=="")
            {
                tempObj = new { code = "error", data = "", message = "用户未登陆！" };
            }
            else
            {
                if (Request.Form["m_code"]!=null)
                {
                    mat.M_CODE = Request.Form["m_code"].ToString();
                    if (mat.M_CODE == "")
                    {
                        tempObj = new { code = "error", data = "", message = "物料编码不能为空！" };
                        return Json(tempObj, JsonRequestBehavior.AllowGet);
                    }
                    else
                    {
                        total++;
                        //物料编码是否存在
                        int count = BLLSession.Current.materialBLL.GetCount(c => c.M_CODE == mat.M_CODE);
                        if(count>0)
                        {
                            tempObj = new { code = "error", data = "", message = "物料编码已存在！" };
                            return Json(tempObj, JsonRequestBehavior.AllowGet);
                        }
                    }
                }
                if (Request.Form["m_specification"]!=null)
                {
                    mat.M_SPECIFICATION = Request.Form["m_specification"].ToString();
                    if (mat.M_SPECIFICATION == "")
                    {
                        tempObj = new { code = "error", data = "", message = "物料规格不能为空！" };
                        return Json(tempObj, JsonRequestBehavior.AllowGet);
                    }
                    else
                    {
                        total++;
                        //物料规格是否存在
                        int count = BLLSession.Current.materialBLL.GetCount(c => c.M_SPECIFICATION == mat.M_SPECIFICATION);
                        if (count > 0)
                        {
                            tempObj = new { code = "error", data = "", message = "物料规格已存在！" };
                            return Json(tempObj, JsonRequestBehavior.AllowGet);
                        }
                    }
                }

                if (Request.Form["m_type"]!=null)
                {
                    mat.M_TYPE = Request.Form["m_type"].ToString();
                    if (mat.M_TYPE == "")
                    {
                        tempObj = new { code = "error", data = "", message = "物料类型不能为空！" };
                        return Json(tempObj, JsonRequestBehavior.AllowGet);
                    }
                    total++;
                }
                if (Request.Form["m_company"]!=null)
                {
                    mat.M_COMPANY = Request.Form["m_company"].ToString();
                    if (mat.M_COMPANY == "")
                    {
                        tempObj = new { code = "error", data = "", message = "厂家不能为空！" };
                        return Json(tempObj, JsonRequestBehavior.AllowGet);
                    }
                    total++;
                }

                if (Request.Form["m_number"]!=null && Request.Form["m_number"].ToString() != "")
                {
                    mat.M_NUMBER = Request.Form["m_number"].ToString();
                    total++;
                }

                if(total!=6)
                {
                    tempObj = new { code = "error", data = "", message = "输入参数不正确！" };
                    return Json(tempObj, JsonRequestBehavior.AllowGet);
                }

                #region 上传图片
                string iurl = "";
                if (Request.Files.Count > 0)
                {
                    HttpPostedFileBase files = Request.Files[0];

                    string imgsize = string.Empty;
                    string error = string.Empty;
                    string FileNames = string.Empty;
                    string TrueFileNames = string.Empty;
                    string imgurl = string.Empty;
                    string str = string.Empty;
                    if (files != null)
                    {
                        long fileSize = 0;
                        fileSize = files.ContentLength;
                        string PicSizeVar = "1024";
                        //上传图片是否已超过了一个限定的值
                        if (fileSize > long.Parse(PicSizeVar) * 1024)
                        {
                            error = "图片超过1M，请重新上传";
                            tempObj = new { code = "error", data = "", message = error };
                            return Json(tempObj, JsonRequestBehavior.AllowGet);
                        }
                        else
                        {
                            double dbsize = Convert.ToDouble(fileSize) / 1024;
                            imgsize = dbsize.ToString("0.00") + "KB";
                            //获取上传文件的名称  
                            string s = files.FileName.Replace(" ", "");
                            //截取获得上传文件的名称(ie上传会把绝对路径也连带上，这里只得到文件的名称)  
                            str = s.Substring(s.LastIndexOf("\\") + 1);
                            FileNames = str;
                            Random r = new Random();
                            str = DateTime.Now.ToString("yyyyMMddHHmmss") + "_" + r.Next(1000).ToString() + "_" + str;//重命名文件，保证每个文件的名称都是唯一的
                            TrueFileNames = str;
                            string path = "~/uploadimages/" + str;
                            files.SaveAs(Server.MapPath(path));
                            imgurl = @"/uploadimages/" + str;
                            iurl = imgurl;
                            //tempObj = new { code = "success", data = "",message = "上传成功！" };
                        }
                    }
                    else
                    {
                        tempObj = new { code = "error", imgurl = "", message = "图片上传失败！" };
                        return Json(tempObj, JsonRequestBehavior.AllowGet);
                    }
                }
                else
                {
                    tempObj = new { code = "error", data = "", message = "请上传图片！" };
                    return Json(tempObj, JsonRequestBehavior.AllowGet);
                }
                #endregion

                if(iurl!="")
                {
                    mat.M_IMGURL = iurl;
                }
                mat.COMPANY_ID = userobj.COMPANY_ID;
                mat.CREATED_BY = userobj.NAME;
                mat.CREATED_TIME = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                BLLSession.Current.materialBLL.Add(mat);
                tempObj = new { code = "success", data = "", message = "添加成功！" };
            }
            return Json(tempObj, JsonRequestBehavior.AllowGet);

        }
        
        //柜子APP：根据物料搜索物料所在的柜子
        public ActionResult search_cabinet()
        {
            var tempObj = new object();
            Stream postData = Request.InputStream;
            StreamReader sRead = new StreamReader(postData);
            string postContent = sRead.ReadToEnd();
            if (postContent == "")
            {
                tempObj = new { code = "error", data = "", message = "输入参数不正确！" };
                return Json(tempObj, JsonRequestBehavior.AllowGet);
            }

            Dictionary<string, object> suggestions = Newtonsoft.Json.JsonConvert.DeserializeObject<Dictionary<string, object>>(postContent);
            
            string sql = "SELECT [CAB_ID],[PRODUCT_ID],[PRODUCT_NO],[DEVICE_ID],[PRODUCT_NAME],[CAB_NAME],[CAB_CODE],[CAB_MARTERIAL_NUMBER],[INVENTORY_NUMBER],[M_CODE],[M_SPECIFICATION],[M_IMGURL],[M_TYPE] FROM [dbo].[vcabinetmaterial] where CAB_STATUS='0' AND ISNULL(CAB_MARTERIAL_ID,'')!='' ";

            if (suggestions.Keys.Contains("device_id") && suggestions["device_id"].ToString() != "")
            {
                string DEVICE_ID = suggestions["device_id"].ToString();
                sql += " AND DEVICE_ID='" + DEVICE_ID + "' ";
            }
            else
            {
                tempObj = new { code = "error", data = "", message = "设备号不能为空！" };
                return Json(tempObj, JsonRequestBehavior.AllowGet);
            }
            if (suggestions.Keys.Contains("m_code") && suggestions["m_code"].ToString()!="")
            {
                string m_code = suggestions["m_code"].ToString();
                sql += " AND m_code = '" + m_code + "' ";
            }
            if (suggestions.Keys.Contains("m_specification") && suggestions["m_specification"].ToString() != "")
            {
                string m_specification = suggestions["m_specification"].ToString();
                sql += " AND m_specification like '" + m_specification + "%' ";
            }
            sql += " ORDER BY CAB_NAME";
            DataTable dt = DBCallCommon.GetDTUsingSqlText(sql);
            if (dt.Rows.Count > 0)
            {
                var data = Commons.Serialize(dt);
                tempObj = new { code = "success", data = data, message = "查询成功！" };
            }
            else
            {
                tempObj = new { code = "success", data = "", message = "未查询到记录！" };
            }
            return Json(tempObj, JsonRequestBehavior.AllowGet);
        }
        //柜子APP：入库
        public ActionResult materialin()
        {
            var tempObj = new object();
            Stream postData = Request.InputStream;
            StreamReader sRead = new StreamReader(postData);
            string postContent = sRead.ReadToEnd();
            if (postContent == "")
            {
                tempObj = new { code = "error", data = "", message = "输入参数不正确！" };
                return Json(tempObj, JsonRequestBehavior.AllowGet);
            }

            Dictionary<string, object> suggestions = Newtonsoft.Json.JsonConvert.DeserializeObject<Dictionary<string, object>>(postContent);

            string cabinet_code = "";
            string device_id = "";
            string token = "";
            if (suggestions.Keys.Contains("token") && suggestions["token"].ToString() != "")
            {
                token = suggestions["token"].ToString();
                var userobj = userController.check_token(token);
                if (userobj == null)
                {
                    tempObj = new { code = "error", data = "", message = "用户未登陆！" };
                    return Json(tempObj, JsonRequestBehavior.AllowGet);
                }
            }
            else
            {
                tempObj = new { code = "error", data = "", message = "token不能为空！" };
                return Json(tempObj, JsonRequestBehavior.AllowGet);
            }

            if (suggestions.Keys.Contains("cabinet_code") && suggestions["cabinet_code"].ToString() != "")
            {
                cabinet_code = suggestions["cabinet_code"].ToString();
            }
            else
            {
                tempObj = new { code = "error", data = "", message = "柜号不能为空！" };
                return Json(tempObj, JsonRequestBehavior.AllowGet);
            }
            if (suggestions.Keys.Contains("device_id") && suggestions["device_id"].ToString() != "")
            {
                device_id = suggestions["device_id"].ToString();
            }
            else
            {
                tempObj = new { code = "error", data = "", message = "设备号不能为空！" };
                return Json(tempObj, JsonRequestBehavior.AllowGet);
            }
            //拆分柜号
            List<int> cabinet_code_list=new List<int>();
            try
            {
                string[] a = cabinet_code.Replace('"', ' ').Replace('[',' ').Replace(']',' ').Split(',');
                for (var i = 0; i < a.Length; i++)
                {
                   cabinet_code_list.Add(Convert.ToInt16(a[i].Trim()));
                }
            }
            catch
            {
                tempObj = new { code = "error", data = "", message = "柜号转换出错！" };
                return Json(tempObj, JsonRequestBehavior.AllowGet);
            }
            //利用device_id设备号和柜号进行入库操作
            if (cabinet_code_list.Count > 0)
            {
                //设备号及柜号对应的智能单元是否存在
                foreach(int code in cabinet_code_list)
                {
                    string sql = "SELECT [CAB_TYPE],ISNULL([INVENTORY_NUMBER],0) INVENTORY_NUMBER FROM [dbo].[vcabinetmaterial] where CAB_STATUS='0' AND CAB_CODE=" + code + " AND DEVICE_ID='" + device_id + "' AND ISNULL(CAB_MARTERIAL_ID,'')!='' ";
                    DataTable dt = DBCallCommon.GetDTUsingSqlText(sql);
                    //不存在可入库记录
                    if (dt.Rows.Count == 0)
                    {
                        tempObj = new { code = "error", data = "", message = "柜号、设备号错误或单元未启用！" };
                        return Json(tempObj, JsonRequestBehavior.AllowGet);
                    }
                    else
                    {
                        if((dt.Rows[0]["CAB_TYPE"].ToString()=="0"||dt.Rows[0]["CAB_TYPE"].ToString()=="1")&& Convert.ToDouble(dt.Rows[0]["INVENTORY_NUMBER"].ToString())>0)
                        {
                            tempObj = new { code = "error", data = "", message = "柜号["+code.ToString()+"]单元存在物料，无法入库！" };
                            return Json(tempObj, JsonRequestBehavior.AllowGet);
                        }
                    }
                }
                //可入库（1入库记录，2时库存表）
                foreach (int code in cabinet_code_list)
                {
                    promaterialin(code,token,device_id);
                }
                tempObj = new { code = "success", data = "", message = "入库成功！" };
            }
            else
            {
                tempObj = new { code = "error", data = "", message = "入库失败，未输入柜号！" };
            }
            return Json(tempObj, JsonRequestBehavior.AllowGet);
        }

        protected void promaterialin(int cabinet_code, string token, string device_id)
        {
            SqlConnection sqlConn = new SqlConnection();
            sqlConn.ConnectionString = DBCallCommon.GetStringValue("connectionStrings");
            DBCallCommon.openConn(sqlConn);
            SqlCommand sqlCmd = new SqlCommand("PRO_MaterialIn", sqlConn);
            sqlCmd.CommandTimeout = 300;
            sqlCmd.CommandType = CommandType.StoredProcedure;
            sqlCmd.Parameters.Add("@cabinet_code", SqlDbType.Int, 4);
            sqlCmd.Parameters["@cabinet_code"].Value = cabinet_code;
            sqlCmd.Parameters.Add("@device_id", SqlDbType.Text, 50);
            sqlCmd.Parameters["@device_id"].Value = device_id;
            sqlCmd.Parameters.Add("@token", SqlDbType.Text, 50);
            sqlCmd.Parameters["@token"].Value = token;
            sqlCmd.ExecuteNonQuery();
            DBCallCommon.closeConn(sqlConn);
        }
        //柜子APP：出库
        public ActionResult materialout()
        {
            var tempObj = new object();
            Stream postData = Request.InputStream;
            StreamReader sRead = new StreamReader(postData);
            string postContent = sRead.ReadToEnd();
            if (postContent == "")
            {
                tempObj = new { code = "error", data = "", message = "输入参数不正确！" };
                return Json(tempObj, JsonRequestBehavior.AllowGet);
            }

            Dictionary<string, object> suggestions = Newtonsoft.Json.JsonConvert.DeserializeObject<Dictionary<string, object>>(postContent);

            string cabinet_code = "";
            string device_id = "";
            string token = "";
            string machinename = "";
            if (suggestions.Keys.Contains("token") && suggestions["token"].ToString() != "")
            {
                token = suggestions["token"].ToString();
                var userobj = userController.check_token(token);
                if (userobj == null)
                {
                    tempObj = new { code = "error", data = "", message = "用户未登陆！" };
                    return Json(tempObj, JsonRequestBehavior.AllowGet);
                }
            }
            else
            {
                tempObj = new { code = "error", data = "", message = "token不能为空！" };
                return Json(tempObj, JsonRequestBehavior.AllowGet);
            }

            if (suggestions.Keys.Contains("cabinet_code") && suggestions["cabinet_code"].ToString() != "")
            {
                cabinet_code = suggestions["cabinet_code"].ToString();
            }
            else
            {
                tempObj = new { code = "error", data = "", message = "柜号不能为空！" };
                return Json(tempObj, JsonRequestBehavior.AllowGet);
            }
            if (suggestions.Keys.Contains("device_id") && suggestions["device_id"].ToString() != "")
            {
                device_id = suggestions["device_id"].ToString();
            }
            else
            {
                tempObj = new { code = "error", data = "", message = "设备号不能为空！" };
                return Json(tempObj, JsonRequestBehavior.AllowGet);
            }

            if (suggestions.Keys.Contains("machinename"))
            {
                machinename = suggestions["machinename"].ToString();
            }
            //拆分柜号
            List<int> cabinet_code_list = new List<int>();
            try
            {
                string[] a = cabinet_code.Replace('"', ' ').Replace('[', ' ').Replace(']', ' ').Split(',');
                for (var i = 0; i < a.Length; i++)
                {
                    cabinet_code_list.Add(Convert.ToInt16(a[i].Trim()));
                }
            }
            catch
            {
                tempObj = new { code = "error", data = "", message = "柜号转换出错！" };
                return Json(tempObj, JsonRequestBehavior.AllowGet);
            }
            //利用device_id设备号和柜号进行出库操作
            if (cabinet_code_list.Count > 0)
            {
                //设备号及柜号对应的智能单元是否存在
                foreach (int code in cabinet_code_list)
                {
                    string sql = "SELECT [CAB_TYPE],ISNULL([INVENTORY_NUMBER],0) INVENTORY_NUMBER FROM [dbo].[vcabinetmaterial] where CAB_STATUS='0' AND CAB_CODE=" + code + " AND DEVICE_ID='" + device_id + "' AND ISNULL(CAB_MARTERIAL_ID,'')!='' ";
                    DataTable dt = DBCallCommon.GetDTUsingSqlText(sql);
                    //不存在可出库记录
                    if (dt.Rows.Count == 0)
                    {
                        tempObj = new { code = "error", data = "", message = "柜号、设备号错误或单元未启用！" };
                        return Json(tempObj, JsonRequestBehavior.AllowGet);
                    }
                    else
                    {
                        if (Convert.ToDouble(dt.Rows[0]["INVENTORY_NUMBER"].ToString()) <= 0)
                        {
                            tempObj = new { code = "error", data = "", message = "柜号[" + code.ToString() + "]单元不存在物料，无法出库！" };
                            return Json(tempObj, JsonRequestBehavior.AllowGet);
                        }
                    }
                }
                //可出库（1出库记录，2即时库存表）
                foreach (int code in cabinet_code_list)
                {
                    promaterialout(code, token, device_id, machinename);
                }
                tempObj = new { code = "success", data = "", message = "出库成功！" };
            }
            else
            {
                tempObj = new { code = "error", data = "", message = "出库失败，未输入柜号！" };
            }
            return Json(tempObj, JsonRequestBehavior.AllowGet);
        }

        protected void promaterialout(int cabinet_code, string token, string device_id, string machinename)
        {
            SqlConnection sqlConn = new SqlConnection();
            sqlConn.ConnectionString = DBCallCommon.GetStringValue("connectionStrings");
            DBCallCommon.openConn(sqlConn);
            SqlCommand sqlCmd = new SqlCommand("PRO_MaterialOut", sqlConn);
            sqlCmd.CommandTimeout = 300;
            sqlCmd.CommandType = CommandType.StoredProcedure;
            sqlCmd.Parameters.Add("@cabinet_code", SqlDbType.Int, 4);
            sqlCmd.Parameters["@cabinet_code"].Value = cabinet_code;
            sqlCmd.Parameters.Add("@device_id", SqlDbType.Text, 50);
            sqlCmd.Parameters["@device_id"].Value = device_id;
            sqlCmd.Parameters.Add("@token", SqlDbType.Text, 50);
            sqlCmd.Parameters["@token"].Value = token;
            sqlCmd.Parameters.Add("@machinename", SqlDbType.Text, 50);
            sqlCmd.Parameters["@machinename"].Value = machinename;
            sqlCmd.ExecuteNonQuery();
            DBCallCommon.closeConn(sqlConn);
        }

    }
}
